<template>
  <div v-if="visible">
    <a-modal
      :title="title"
      :width="1000"
      :visible="visible"
      @cancel="handleCancel"
      destroyOnClose
      :footer="null">
      <a-upload-dragger
        v-if="!pageShow"
        name="file"
        :showUploadList="false"
        :disabled="fileList.length>=1"
        listType="picture-card"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        :multiple="false"
        :headers="headers"
        :beforeUpload="beforeUpload"
        :action="importExcelUrl"
      >
        <!--      @change="handleImportExcel"-->
        <!--     :beforeUpload="beforeUpload"  -->
        <div style="min-height: 260px;display: flex;justify-content: center;align-items: center;flex-direction: column">
          <p class="ant-upload-drag-icon">
            <a-icon type="cloud" :style="{ fontSize: '80px', color: '#1890ff' }"/>
          </p>
          <p class="ant-upload-text" v-if="fileList.length<1">
            将文件拖到此处，或<a>点击上传</a>
          </p>
          <div v-if="fileList.length>=1" style="display: flex;align-items: center;">
            <a >{{fileName||''}}</a>
            <span style="margin-left: 10px;">
            <a-icon type="close"  @click="()=>{fileList=[]}"/>
         </span>
          </div>
        </div>
      </a-upload-dragger>
      <div v-if="!pageShow">
        只能上传excel文件，且不能超过5MB
      </div >
      <div v-if="pageShow">
        <div id="upload-box" class="upload-box">
          <div v-for="(v,i) in list" :key="i">{{v}}</div>
        </div>
      </div>
      <div style="text-align: right;margin-top:60px">
        <a-button type="primary" @click="handleUpload" style="margin-right: 10px">开始上传</a-button>
        <a-button type="primary" @click="handleGoOn" style="margin-right: 10px">继续上传</a-button>
        <a-button type="primary" @click="handleExportXls(url.exportName)" style="margin-right: 10px">下载模版</a-button>
        <a-button type="danger" icon="close" @click="close" >关闭</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { WebsocketMixin } from '@/mixins/WebsocketMixin'
import { downFile, httpAction,postAction } from '@/api/manage'
import {pick} from 'lodash'
import moment from "moment"
import JTreeSelect from "@/components/cn-form/JTreeSelect";
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import {isMobile} from "@/utils/validate";
import UploadImage from '@/components/upload-image/UploadImage'
import {isNil} from 'lodash'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { axios } from '@/utils/request'
// import {PageListMixin} from '@/mixins/PageListMixin'
export default {
  name: "uploadExcel",
  // mixins: [WebsocketMixin],
  props: {
    limit: {
      type: Number,
      default: () => 1
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      title:'导入文件',
      pageShow:false,
      fileName:'',
      visible:false,
      uploadAction: window._CONFIG['domianZhantuURL'] + "/zhantuBudget/importExcel",
      fileList: [],
      list:['请等待···'],
      headers: {},
      url: {
        importExcelUrl:'',
        exportXlsUrl: '',
        exportName:'',
        setTopic:''
      },
    }
  },
  components: {JTreeSelect, JAreaLinkage, UploadImage},
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = {loginUserToken: token}
  },
  watch:{
  },
  destroyed: function () {
    // 离开页面生命周期函数
    this.websocketOnclose();
  },
  methods: {
    setTopic(){
      return this.url.setTopic
    },
    websocketOnmessage(e){
      const redata = JSON.parse(e.data);
      if(redata.success){
        let msg = redata.message
        this.list.push(msg)
        if(this.list.length>=100){
          this.list.splice(1,1);
        }
        this.$nextTick(() => {
          try {
            var div = document.getElementById('upload-box');
            div.scrollTop = div.scrollHeight;
          }catch (err){
            console.log(err)
          }
        })
      }
    },

    beforeUpload(file) {
      console.log(file)
      const isLt2M = file.size / 1024 / 1024 < 5;
      console.log(isLt2M)
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 5MB!');
        return
      }
      // this.fileList = [...this.fileList, file];
      this.fileName = file.name;
      this.fileList = [file];
      return false;
    },
    handleUpload() {
      const { fileList=[] } = this;
      if(fileList.length<1){
        this.$message.warning('请选择文件后再上传！')
        return
      }
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('file', file);
      });
      postAction(this.importExcelUrl(),formData).then(res=>{
        if(res.success){
          this.fileList = [];
          this.pageShow=true
          this.$message.info('请等待，正在导入···');
        }else {
          this.uploading = false;
          this.$message.error('导入失败');
        }

      })
    },
    importExcelUrl: function() {
      return `${this.url.importExcelUrl}`;
    },
    /* 导入 */
    handleImportExcel(info) {
      console.log(info)
      const isLt2M = info.file.size / 1024 / 1024 < 5;
      // console.log(isLt2M)
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 5MB!');
        return
      }
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: ('<div><span>{msg}</span><br/> <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span> </div>'
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.pageShow=true
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },

    add(url) {
      this.edit({},url);
    },

    edit(record,url) {
      this.visible = true;
      if(url){
        this.url = url
      }
      this.initWebSocket();
    },

    handleGoOn(){
      this.pageShow=false;
      this.list=['请等待···']
    },

    close() {
      this.$emit('close');
      this.visible = false;
      this.pageShow=false;
      this.list=['请等待···']
      this.websocketOnclose()
    },

    handleCancel() {
      this.close()
    },

    customRequest(e){
      console.log(e)
    },

    // downFile(url, parameter) {
    //   return axios({
    //     url: url,
    //     params: parameter,
    //     method: 'get',
    //     responseType: 'blob'
    //   })
    // },

    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        console.log(data)
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },

    initWebSocket: function () {
      console.log("------------WebSocket正在连接");
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var token =Vue.ls.get('Access-Token')
      var url = window._CONFIG['domianSocketURL'].replace("https://","wss://").replace("http://","ws://") + '/websocket/' + token.loginUserToken+'/' + this.setTopic();
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },

    websocketOnopen: function () {
      console.log("WebSocket连接成功");
    },

    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },

    websocketOnclose: function (e) {
      // this.reconnect();
      try {
        this.websock.close();
      } catch (error){
        console.log(error)
      }
    },

    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },

    reconnect() {
      var that = this;
      if(that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 1000);
    },
  }
}
</script>

<style scoped>
.upload-box{
  position: relative;
  width: 100%;
  height: 260px;
  text-align: left;
  padding: 10px 20px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
  overflow-y: scroll;
}
</style>
